package com.zf.shuashua.advert;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;

import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.bean.AdvertInfo;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.utils.Util;

import java.io.File;

public class AdManager {

    private static final String PLAN_ID = "id";
    private static final String UUID = "uuid";
    private static final String THUMB_NAIL = "thumbnail";
    private static final String ORIGINAL_URL = "original_url";
    private static final String CLICK_URL = "click_url";
    private static final String LINK_TYPE = "link_type";

    private SharedPreferences sp;

    private CompleteReceiver mCompleteReceiver;

    private static class SingletonHolder {
        private static final AdManager INSTANCE = new AdManager();
    }

    public static AdManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private AdManager() {
        sp = ShuaApplication.getContext().getSharedPreferences("ad", Context.MODE_PRIVATE);
    }

    public void onDestroy(Context context) {
        try {
            if (mCompleteReceiver != null) {
                context.unregisterReceiver(mCompleteReceiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadAdvert(Context context) {
        try {
            String path = Environment.getExternalStorageDirectory() + "/ad";
            Util.deleteDir(new File(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            sp.edit().clear().apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpData.getInstance().getAdvertOpen(new ACallback<BaseData<AdvertInfo>>() {
            @Override
            public void onSuccess(BaseData<AdvertInfo> data) {
                if (data.getData() != null) {
                    AdvertInfo videoInfo = data.getData();
                    sp.edit().putString(PLAN_ID, videoInfo.plan_id + "").apply();
                    sp.edit().putString(UUID, videoInfo.getUuid()).apply();
                    sp.edit().putString(THUMB_NAIL, videoInfo.thumbnail).apply();
//                    sp.edit().putString(ORIGINAL_URL, videoInfo.origin_url).apply();
                    sp.edit().putString(CLICK_URL, videoInfo.getClick_url()).apply();
                    sp.edit().putString(LINK_TYPE, videoInfo.link_type).apply();

                    if (videoInfo.isVideo()) {
                        downloadVideo(context, videoInfo);
                    }
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });
    }

    public String getPlanId() {
        return sp.getString(PLAN_ID, "");
    }

    public String getUuid() {
        return sp.getString(UUID, "");
    }

    public String getThumbNail() {
        return sp.getString(THUMB_NAIL, "");
    }

    public String getClickUrl() {
        return sp.getString(CLICK_URL, "");
    }

    public String getLinkType() {
        return sp.getString(LINK_TYPE, "");
    }

    public String getOriginalUrl() {
        return sp.getString(ORIGINAL_URL, "");
    }

    private void downloadVideo(Context context, AdvertInfo info) {
        try {
            Uri uri = Uri.parse(info.origin_url);
            DownloadManager.Request request = new DownloadManager.Request(uri);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            request.setVisibleInDownloadsUi(true);
            request.setDestinationInExternalPublicDir("ad", "/video.mp4");
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            downloadManager.enqueue(request);

            mCompleteReceiver = new CompleteReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            context.registerReceiver(mCompleteReceiver, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveVideo() {
        String path = Environment.getExternalStorageDirectory() + "/ad/video.mp4";
        sp.edit().putString(ORIGINAL_URL, path).apply();
    }

    static class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action!=null && action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                AdManager.getInstance().saveVideo();
            }
        }
    }
}
